<?php
namespace app\api\model;


use think\Model;
use app\api\model\traits\GoodsTrait;
class Order extends Common
{
	use GoodsTrait;
	public function createOrder($userId,$addressId,$payWay,$expressWay,$invoiceType,$invoiceHeader,$invoiceContent,$cartIds=[]){

		$cart = new Cart();
		$where = [
			['user_id','=',$userId]
		];
		if(!empty($cartIds)){
			$where[]= ['id','in',$cartIds];
		}
		$goodsList = $cart->where($where)->with('goods')->select();
		if(empty($goodsList)){
			$this->error = '购物车中无数据|600';
			return false;
		}
		// 计算总金额
		$money = 0;
		foreach ($goodsList as $key => $value) {
			$money += $value['goods_count'] * $value->goods->shop_price;
		}
		$order = new Order;
		$order->user_id = $userId;
		$order->address_id = $addressId;
		$order->order_sn = date('YmdHis').rand(1000,9999);
		$order->pay_way = $payWay;
		$order->express_way = $expressWay;
		$order->invoice_type = $invoiceType;
		$order->invoice_header = $invoiceHeader;
		$order->invoice_content = $invoiceContent;
		$order->money = $money;
		$order->save();


		// 订单详情入库
		$cartDetail = [];
		foreach ($goodsList as $key => $value) {
			$cartDetail[]=[
				'order_id'=>$order->id,
				'goods_id'=>$value->goods_id,
				'goods_count'=>$value->goods_count,
				'goods_attr_ids'=>$value->goods_attr_ids
			];
		}
		(new OrderDetail)->saveAll($cartDetail);

		// 清除用户购物车
		$cart->where($where)->delete();
		return $order;
	}

	public function orderDetail()
	{
		return $this->hasMany(OrderDetail::class,'order_id','id');
	}
}